package com.example.system.class07;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Date 2022/7/24
 * @Created by Jonathan
 */
public class Code01_Comparator {
    public static void main(String[] args) {


        List<Student> list = new ArrayList<>();
        list.add(new Student(2, "张三", "男"));
        list.add(new Student(2, "张", "男"));
        list.add(new Student(1, "李四", "男"));
        list.add(new Student(3, "王五", "男"));
        System.out.println(list);
        list.sort(new IdAscendingComparator());
        System.out.println("========after sort==============");
        System.out.println(list);

    }

    static class Student {

        private Integer id;
        private String name;
        private String gender;

        public Student(Integer id, String name, String gender) {
            this.id = id;
            this.name = name;
            this.gender = gender;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", gender='" + gender + '\'' +
                    '}';
        }
    }

    // 返回负数的时候 第一个参数排在前面
    // 返回正数的时候 第二个参数排在前面
    // 返回0的时候 认为谁排在前面无所谓
    static class IdAscendingComparator implements Comparator<Student> {
        @Override
        public int compare(Student s1, Student s2) {
            // id 相同的情况下比较姓名!
            return (s1.id - s2.id) == 0 ? (s1.name.compareTo(s2.name)) : s1.id - s2.id;
        }
    }
}
